<?php
namespace Admin\Controller;
use Think\Controller;
class ArticleController extends BaseController {
    public function addArticle(){
		if(IS_POST){			
			$article = D('article');
			//数据是否符合规则
			if(!$article->create() ){
				$this->error($article->getError(),U('addArticle'),1 );
				return;
			}
			//对上传图片做处理
			if( $_FILES['pic']['tmp_name']!='' ){
				
				$this->upload($article);
			}
			$article->atime = date('y-m-d h:i:s',time());
			//是否添加成功
			if( $article->add()){
				$this->success('添加成功',U('addArticle'),1 );
			}else{
				$this->error('添加失败',U('addArticle'),1 );
			}
			return;
		}
		
        $type = M('type');
		$type = $type->select();
		$this->type = $type;
		$this->display();
    }
	
	public function showArticle(){
		$article = D('article');
		$count = $article->count();
		$Page = new \Think\Page($count,3);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$Page->setConfig('prev','上一页');
		$Page->setConfig('next','下一页');
		$show = $Page->show();// 分页显示输出
		$typeRes = $article->limit($Page->firstRow.','.$Page->listRows)->select();//数据
		$this->page = $show;
		$this->articleRes = $typeRes;
		$this->num = 1; //用于标记栏目数
        $this->display();
	}
	
	public function updateArticle(){
		if(IS_POST){			
			$article = D('article');
			//数据是否符合规则
			if(!$article->create() ){
				$this->error($article->getError(),U('addArticle'),1 );
				return;
			}
			//对上传图片做处理
			if( $_FILES['pic']['tmp_name']!='' ){
				
				$this->upload($article);
			}
			$article->atime = date('y-m-d h:i:s',time());
			//是否添加成功
			if( $article->save()){
				$this->success('修改成功',U('showArticle'),1 );
			}else{
				$this->error('修改失败',U('updateArticle'),1 );
			}
			return;
		}
	
	
		$aid = I('aid');
		$article = D('article');
		$oneArticle = $article->relation(true)->find($aid);
		$this->oneArticle = $oneArticle;
		
		$type = M('type');
		$type = $type->select();
		$this->type = $type;
		
		$this->display();
	}
	
	public function deleteArticle(){
		$article = D('article');
		$date['aid'] = I('aid');
		if( $article->create($date) ){
			$this->success('删除成功',U('showArticle'),1 );
		}else{
			$this->error('删除失败',U('showArticle'),1 );
		}
	}
	
	private function upload($article){
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize = 3145728 ;// 设置附件上传大小
		$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->rootPath = './'; // 设置附件上传根目录
		$upload->savePath = './Public/Uploads/'; // 设置附件上传（子）目录
		// 上传文件
		$info = $upload->uploadOne($_FILES['pic']);
		if(!$info) {// 上传错误提示错误信息
			$this->error($upload->getError());
		}else{// 上传成功 获取上传文件信息
			$article->pic= $info['savepath'].$info['savename'];
		}
	}
	
}